//
//  ZZExprMgr.m
//  ZZExprLib
//
//  Created by Layzhao on 2018/7/4.
//  Copyright © 2018年 Layzhao. All rights reserved.
//

#import "ZZExprMgr.h"
#import <YYCache.h>
#import <YYModel.h>

#define ZZEXPR_FILENAME @"exprConfig.conf"

@interface ZZExprMgr()

@property (nonatomic, strong) NSMutableDictionary *dicCacheExprConfigItems;
@property (nonatomic, strong) YYCache *cache;

@end

@implementation ZZExprMgr

static NSRecursiveLock* oLock;

+ (instancetype)sharedManager
{
    static ZZExprMgr *mgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mgr = [ZZExprMgr new];
    });
    return mgr;
}

- (instancetype)init
{
    if(self = [super init]) {
        oLock = [[NSRecursiveLock alloc] init];
        _userId = @"";
        _cache = [YYCache cacheWithName:ZZEXPR_FILENAME];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updateExprConfig
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self realUpdateExprConfig];
    });
}

- (void)realUpdateExprConfig
{
    if (self.userId.length == 0) {
        return;
    }
    
#warning 请求更新接口
//    ZZExprConfigTask *task = [[ZZExprConfigTask alloc] init];
//    [self ZZ_executeNetworkTask:task success:^(id responseModel) {
//        if ([responseModel isKindOfClass:[ZZExprConfigItems class]]) {
//            //设为空，重新去本地拉取数据
//            [oLock lock];
//            //移除测试代码，每次update时，增量更新
//            //                self.dicCacheExprConfigItems = nil;
//            ZZExprConfigItems *respConfigItems = (ZZExprConfigItems *)responseModel;
//            for (ZZExprItem *item in respConfigItems.list) {
//                if(item.featureCode.length == 0) {
//                    continue;
//                }
//                [self.dicCacheExprConfigItems setObject:item.value forKey:item.featureCode];
//            }
//            [oLock unlock];
//            [self saveDicCacheExprConfigItems];
//        }
//    } failure:^(NSError *error) {
//    }];
}

- (void)clearExprConfig
{
    self.userId = @"";
    self.dicCacheExprConfigItems = nil;
}

- (NSString *)getExptWithFeatureCode:(NSString *)featureCode withValueKey:(NSString *)valueKey withStringDefault:(NSString *)defaultValue
{
    if(featureCode.length == 0 || valueKey.length == 0) {
        return defaultValue;
    }
    
    NSString *value = [self getExptWithFeatureCode:featureCode withValueKey:valueKey];
    if([value isKindOfClass:[NSString class]]) {
        return value;
    }
    else if([value isKindOfClass:[NSNumber class]]) {
        return [(NSNumber *)value stringValue];
    }
    return defaultValue;
}

- (BOOL)getExptWithFeatureCode:(NSString *)featureCode withValueKey:(NSString *)valueKey withBoolDefault:(BOOL)defaultValue
{
    if(featureCode.length == 0 || valueKey.length == 0) {
        return defaultValue;
    }
    
    id value = [self getExptWithFeatureCode:featureCode withValueKey:valueKey];
    if([value isKindOfClass:[NSString class]]) {
        return [((NSString *)value) boolValue];
    }
    else if([value isKindOfClass:[NSNumber class]]) {
        return [((NSNumber *)value) boolValue];
    }
    return defaultValue;
}

- (id)getExptWithFeatureCode:(NSString *)featureCode withValueKey:(NSString *)valueKey
{
    id value = nil;
    [oLock lock];
    if(featureCode.length > 0 && valueKey.length > 0) {
        id obj = [self.dicCacheExprConfigItems objectForKey:featureCode];
        if([obj isKindOfClass:[NSDictionary class]]) {
            value = [(NSDictionary *)obj objectForKey:valueKey];
        }
    }
    [oLock unlock];
    return value;
}

#if (defined DEBUG) || (defined ADHOC)
- (NSMutableDictionary *)getAllExpt
#else
- (NSDictionary *)getAllExpt
#endif
{
    return self.dicCacheExprConfigItems;
}

#pragma mark - getter
- (NSString *)userId
{
    return _userId;
}

- (NSMutableDictionary *)dicCacheExprConfigItems
{
    if(_dicCacheExprConfigItems == nil) {
        if(self.userId.length > 0) {
            //从本地获取
            [oLock lock];
            id dic = [self fetchDocumentObjectForUserId:self.userId];
            if([dic isKindOfClass:[NSDictionary class]]) {
                _dicCacheExprConfigItems = [NSMutableDictionary dictionaryWithDictionary:dic];
            }
            else {
                //清空文件
                [self removeDocumentObjectForUserId:self.userId];
                _dicCacheExprConfigItems = [NSMutableDictionary dictionary];
            }
            [oLock unlock];
        }
        else {
            _dicCacheExprConfigItems = [NSMutableDictionary dictionary];
        }
    }
    return _dicCacheExprConfigItems;
}

- (BOOL)saveDicCacheExprConfigItems
{
    [oLock lock];
    BOOL ret = [self storeDocumentObj:self.dicCacheExprConfigItems forUserId:self.userId];
    [oLock unlock];
    
    return ret;
}

#pragma mark - private
- (BOOL)storeDocumentObj:(id)obj forUserId:(NSString *)userId
{
    if(!obj || userId.length == 0) {
        NSLog(@"%@ userId: %@, obj: %@", NSStringFromSelector(_cmd), userId, obj);
        return NO;
    }
    //获取path
    [self.cache setObject:obj forKey:userId];
    return YES;
}

- (id)fetchDocumentObjectForUserId:(NSString *)userId
{
    if(userId.length == 0) {
        NSLog(@"%@ userId: %@", NSStringFromSelector(_cmd), userId);
        return nil;
    }
    id ret = [self.cache objectForKey:userId];
    return ret;
}

- (BOOL)removeDocumentObjectForUserId:(NSString *)userId
{
    if(userId.length == 0) {
        NSLog(@"%@ userId: %@", NSStringFromSelector(_cmd), userId);
        return NO;
    }
    [self.cache removeObjectForKey:userId];
    return YES;
}

@end
